import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default {
	install(wf) {
		const store = new Vuex.Store({
			state: {
				userInfo: {
					isLogin: false,
					name: '',
					nickName: '',
					userId: '',
					telephone: null,
					coupons: [],
				},
				cartList: [],
			},
			getters: {
				cartMapList: (state) => {
					const list = state.cartList;
					const mapList = [];
					const map = {};
					list.forEach((item) => {
						const id = item.productId;
						if (!map[id]) {
							map[id] = [];
						}
						map[id].push(item);
					});
					Object.keys(map).forEach((productId) => {
						let productItems = map[productId];
						let productItem = productItems[0];
						let count = productItems.length;
						let pricePay =
							(count * parseFloat(productItem.price)) / 100.0;
						// console.log('productItem', productItem);
						mapList.push({
							...productItem,
							count,
							pricePay,
						});
					});
					return mapList;
				},
			},
			mutations: {
				addCart(state, { item }) {
					state.cartList.push(item);
				},
				delCart(state, { item }) {
					state.cartList.splice(
						state.cartList.findIndex(
							(i) => i.productId === item.productId
						),
						1
					);
				},
				clearCart(state, payload) {
					state.cartList = [];
				},
				updateUserInfo(state, userInfo) {
					Object.assign(state.userInfo, userInfo);
				},
			},
		});

		wf.addModule('store', store);
	},
};
